<template>
  <div class="container">
    <div class="push-container">
      <div class="header"><span class="header-icon"></span><span class="header-title">发布图文</span></div>
      <div class="img-list">
        <el-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleRemove"
            :limit="9"
            multiple
            :before-upload="beforeUpload"
            accept="image/*"
            :on-exceed="handleExceed"
            :on-progress="handleProgress"
        >
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="upload-progress" v-if="uploading">
              <el-progress
                  :percentage="progressPercent"
                  :stroke-width="16"
                  :format="formatProgress"
              />
            </div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </div>
      <el-divider style="margin: 12px; width: 576px" />
      <div class="push-content">
        <el-input
          v-model="title"
          maxlength="20"
          show-word-limit
          type="text"
          placeholder="请输入标题"
          class="input-title"
        />
        <el-input
          :rows="5"
          v-model="content"
          maxlength="2000"
          show-word-limit
          type="textarea"
          placeholder="请输入正文"
          class="input-content"
        />
      </div>

      <!-- 添加位置选择 -->
      <div class="location-section">
        <div class="section-title">添加位置</div>
        <div class="search-box-wrapper">
          <el-input
            v-model="searchKeyword"
            placeholder="输入地址搜索"
            :disabled="searching"
            @keyup.enter="handleSearch"
            class="search-input"
          >
            <template #append>
              <el-button :icon="Search" @click="handleSearch" :loading="searching">
                搜索
              </el-button>
            </template>
          </el-input>
          <div v-if="searchResults.length > 0" class="search-results">
            <div
              v-for="(item, index) in searchResults"
              :key="index"
              class="search-result-item"
              @click="handleSelectSearchResult(item)"
            >
              <span class="result-name">{{ item.name }}</span>
              <span class="result-address">{{ item.address || item.district }}</span>
            </div>
          </div>
        </div>

        <div class="map-wrapper">
          <el-amap
            class="amap-box"
            :zoom="mapConfig.zoom"
            :zooms="mapConfig.zooms"
            :center="mapConfig.center"
            @init="handleMapInit"
            @click="handleMapClick"
          >
            <!-- 标记 -->
            <el-amap-marker
              :position="locationMarker.position"
              :visible="locationMarker.visible"
            />
          </el-amap>

          <div v-if="selectedPosition && locationMarker.visible" class="selected-location">
            <el-tag>已选择位置: {{ selectedAddress }}</el-tag>
            <el-button type="primary" link @click="clearLocation">清除</el-button>
          </div>
        </div>
      </div>

<!--      <div class="btns">-->
<!--        <button class="css-fm44j css-osq2ks dyn">-->
<!--          <span class="btn-content"># 话题</span></button-->
<!--        ><button class="css-fm44j css-osq2ks dyn">-->
<!--          <span class="btn-content"><span>@</span> 用户</span></button-->
<!--        ><button class="css-fm44j css-osq2ks dyn">-->
<!--          <span class="btn-content"-->
<!--            ><div class="smile"></div>-->
<!--            表情</span-->
<!--          >-->
<!--        </button>-->
<!--      </div>-->
      <div class="submit">
        <el-button type="primary" @click="publish('pendingReview')">发布</el-button>
        <el-button type="info" @click="publish('draft')">存为草稿</el-button>
        <el-button @click="resetForm">取消</el-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { Plus, Search } from "@element-plus/icons-vue";
import { TravelNoteApi } from "@/api/new/travelNoteApi";
import {UploadProps, UploadFile, ElMessage, ElLoading} from "element-plus";
import router from "@/router";
import UserUtil from "@/utils/User/User";

interface UploadFileWithUrl extends UploadFile {
  responseUrl?: string; // 添加自定义响应字段
}

const fileList = ref<UploadFileWithUrl[]>([]);
const uploadedUrls = ref<string[]>([]); // 存储成功上传的URL
const progressPercent = ref(0);
const uploading = ref(false);
const title = ref('');
const content = ref('');
const dialogVisible = ref(false);
const dialogImageUrl = ref('');

// 地图相关
const mapConfig = reactive({
  zoom: 15,
  zooms: [3, 20],
  center: [116.397428, 39.90923], // 默认北京
});

// 地图标记
const locationMarker = reactive({
  position: [116.397428, 39.90923],
  visible: false,
});

// 地图实例
let mapInstance = null;
let AMapSearch = null; // 搜索服务

// 搜索相关
const searchKeyword = ref('');
const searching = ref(false);
const searchResults = ref([]);

// 位置相关状态
const selectedPosition = ref<{ lng: number; lat: number } | null>(null);
const selectedAddress = ref('');

// 处理地图初始化
const handleMapInit = (map) => {
  console.log('地图初始化成功');
  mapInstance = map;

  // 初始化搜索服务
  if (window.AMap && window.AMap.service) {
    AMapSearch = new window.AMap.service.PlaceSearch({
      pageSize: 10,
      pageIndex: 1,
    });
  }

  // 尝试获取当前位置
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { longitude, latitude } = position.coords;
        mapConfig.center = [longitude, latitude];
        if (mapInstance) {
          mapInstance.setCenter([longitude, latitude]);
        }
      },
      (error) => {
        console.error('获取位置失败:', error);
      }
    );
  }
};

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词');
    return;
  }

  searching.value = true;
  searchResults.value = [];

  if (AMapSearch) {
    AMapSearch.search(searchKeyword.value, (status, result) => {
      searching.value = false;

      if (status === 'complete' && result.info === 'OK') {
        searchResults.value = result.poiList.pois || [];
      } else {
        ElMessage.warning('搜索结果为空，请尝试其他关键词');
      }
    });
  } else if (window.AMap && window.AMap.plugin) {
    // 如果没有初始化搜索服务，尝试使用插件方式
    window.AMap.plugin('AMap.PlaceSearch', () => {
      const placeSearch = new window.AMap.PlaceSearch({
        pageSize: 10,
        pageIndex: 1,
      });

      placeSearch.search(searchKeyword.value, (status, result) => {
        searching.value = false;

        if (status === 'complete' && result.info === 'OK') {
          searchResults.value = result.poiList.pois || [];
        } else {
          ElMessage.warning('搜索结果为空，请尝试其他关键词');
        }
      });
    });
  } else {
    searching.value = false;
    ElMessage.error('搜索服务初始化失败');
  }
};

// 选择搜索结果
const handleSelectSearchResult = (item) => {
  if (item && item.location) {
    const { lng, lat } = item.location;

    console.log(`设置标记位置: [${lng}, ${lat}]`);

    // 更新选择的位置
    selectedPosition.value = { lng, lat };

    // 更新标记位置
    locationMarker.position = [lng, lat];
    locationMarker.visible = true;

    // 更新地址文本
    selectedAddress.value = item.address || item.name || `位置坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}`;

    // 更新地图中心
    mapConfig.center = [lng, lat];

    // 确保地图中心移动到选择的位置
    if (mapInstance) {
      mapInstance.setCenter([lng, lat]);
    }

    // 清空搜索结果
    searchResults.value = [];
  }
};

// 处理地图点击
const handleMapClick = (e) => {
  console.log('地图点击事件:', e);
  const { lng, lat } = e.lnglat;
  selectedPosition.value = { lng, lat };
  locationMarker.position = [lng, lat];
  locationMarker.visible = true;

  // 这里应该调用高德地图API进行逆地理编码
  // 由于没有实际API，这里使用模拟数据
  selectedAddress.value = `位置坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}`;

  // 清空搜索结果
  searchResults.value = [];
};

// 清除选择的位置
const clearLocation = () => {
  selectedPosition.value = null;
  selectedAddress.value = '';
  locationMarker.visible = false;
};

// 发布逻辑增强
const publish = async (status = 'pendingReview') => {
  if (!validateForm(status)) return;

  const loading = ElLoading.service({
    lock: true,
    text: status === 'draft' ? '正在保存草稿...' : '正在发布中...',
  });

  try {
    const params = {
      authorID: getCurrentUserID(),
      title: title.value,
      content: content.value,
      img_url: uploadedUrls.value,
      latitude: selectedPosition.value?.lat || 0,
      longitude: selectedPosition.value?.lng || 0,
      location: selectedAddress.value || '',
      status: status,
    };
    console.log('上传params',params);

    await TravelNoteApi.publishTravelNote(params);
    ElMessage.success(status === 'draft' ? '草稿保存成功！' : '发布成功！');
    router.push('/user/note');
  } finally {
    loading.close();
  }
};

// 重置表单
const resetForm = () => {
  title.value = '';
  content.value = '';
  fileList.value = [];
  uploadedUrls.value = [];
  selectedPosition.value = null;
  selectedAddress.value = '';
  locationMarker.visible = false;
};

// 表单验证
const validateForm = (status) => {
  const errors = [];
  if (!title.value?.trim()) errors.push('请填写标题');
  
  // 如果是发布，则需要验证内容和图片
  if (status === 'pendingReview') {
    if (!content.value?.trim()) errors.push('请填写内容');
    if (uploadedUrls.value.length < 1) errors.push('至少需要上传一张图片');
  } else if (status === 'draft') {
    // 草稿模式下，只要有标题即可
    if (!content.value?.trim() && uploadedUrls.value.length < 1) {
      errors.push('请填写内容或上传图片');
    }
  }

  if (errors.length > 0) {
    ElMessage.warning(errors.join('，'));
    return false;
  }
  return true;
};

// 获取当前用户ID（示例）
const getCurrentUserID = () => {
  return UserUtil.getUserId();
};

// 处理文件变化
const handleFileChange: UploadProps["onChange"] = async (uploadFile) => {
  try {
    // 仅处理当前变化的文件（单文件模式）
    if (!uploadFile.raw) return;

    // 检查是否已存在
    const exists = fileList.value.some(f => f.uid === uploadFile.uid);
    if (exists) return;

    // 添加loading状态
    const tempFile = {
      ...uploadFile,
      status: 'uploading',
      percentage: 0
    } as UploadFileWithUrl;

    fileList.value = [...fileList.value, tempFile];

    // 单文件上传
    const res = await TravelNoteApi.uploadImage(uploadFile.raw);

    // 更新状态
    fileList.value = fileList.value.map(f =>
        f.uid === uploadFile.uid
            ? { ...f, status: 'success', responseUrl: res.url }
            : f
    );

    console.log('上传结果',res);

    uploadedUrls.value = [...uploadedUrls.value, res];

    console.log('更新图片url数组：',uploadedUrls.value);
  } catch (error) {
    // 错误处理
    fileList.value = fileList.value.map(f =>
        f.uid === uploadFile.uid
            ? { ...f, status: 'fail' }
            : f
    );
  }
};

// 文件移除处理
const handleRemove: UploadProps["onRemove"] = (file) => {
  uploadedUrls.value = uploadedUrls.value.filter(url => url !== (file as UploadFileWithUrl).responseUrl);
};

// 文件类型和大小验证
const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!['image/jpeg', 'image/png', 'image/webp'].includes(rawFile.type)) {
    ElMessage.error('仅支持 JPG/PNG/WEBP 格式');
    return false;
  }
  if (rawFile.size > 5 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过5MB');
    return false;
  }
  return true;
};

// 超出限制处理
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.warning('最多可上传9张图片');
};

// 进度处理
const handleProgress: UploadProps['onProgress'] = (event) => {
  progressPercent.value = Math.floor(event.percent);
  uploading.value = true;
};

const formatProgress = () => {
  return `${progressPercent.value}%`;
};

// 获取当前位置
onMounted(() => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { longitude, latitude } = position.coords;
        mapConfig.center = [longitude, latitude];
      },
      (error) => {
        console.error('获取位置失败:', error);
      }
    );
  }
});
</script>

<style lang="less" scoped>
:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}
:deep(.el-upload-list__item.is-success .el-upload-list__item-status-label) {
  display: none;
}
:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
}

.container {
  flex: 1;
  padding: 0 24px;
  width: 67%;
  max-width: 900px;
  margin: 0 auto;
  .push-container {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .header {
      padding: 15px 20px;
      line-height: 16px;
      font-size: 16px;
      font-weight: 400;

      .header-icon {
        position: relative;
        top: 2px;
        display: inline-block;
        width: 6px;
        height: 16px;
        background: #ff2442;
        border-radius: 3px;
        margin-right: 2px;
      }
    }

    .img-list {
      width: 90%;
      margin: auto;
      padding: 0px 6px 0px 6px;
    }

    .location-section {
      padding: 12px;
      margin: 12px;
      border: 1px solid #eee;
      border-radius: 4px;

      .section-title {
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 12px;
      }

      .search-box-wrapper {
        position: relative;
        margin-bottom: 10px;
        z-index: 1000;

        .search-input {
          margin-bottom: 12px;
        }

        .search-results {
          position: absolute;
          top: 100%;
          left: 0;
          right: 0;
          background: white;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          max-height: 300px;
          overflow-y: auto;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

          .search-result-item {
            padding: 10px 15px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;

            &:hover {
              background-color: #f5f7fa;
            }

            &:last-child {
              border-bottom: none;
            }

            .result-name {
              display: block;
              font-weight: bold;
              margin-bottom: 3px;
            }

            .result-address {
              display: block;
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }

      .map-wrapper {
        width: 100%;
        margin-bottom: 16px;

        .amap-box {
          width: 100%;
          height: 300px;
          margin-bottom: 10px;
        }

        .selected-location {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-top: 8px;
        }
      }
    }

    .push-content {
      padding: 0 12px 10px 12px;

      .input-title {
        margin-bottom: 5px;
        font-size: 12px;
      }

      .input-content {
        font-size: 12px;
      }
    }
    .btns {
      padding: 0 12px 10px 12px;
      button {
        min-width: 62px;
        width: 62px;
        margin: 0 6px 0 0;
        height: 18px;
      }

      .css-fm44j {
        -webkit-font-smoothing: antialiased;
        appearance: none;
        font-family:
          RedNum,
          RedZh,
          RedEn,
          -apple-system;
        vertical-align: middle;
        text-decoration: none;
        border: 1px solid rgb(217, 217, 217);
        outline: none;
        user-select: none;
        cursor: pointer;
        display: inline-flex;
        -webkit-box-pack: center;
        justify-content: center;
        -webkit-box-align: center;
        align-items: center;
        margin-right: 16px;
        border-radius: 4px;
        background-color: white;
        color: rgb(38, 38, 38);
        height: 24px;
        font-size: 12px;
      }
    }
    .submit {
      padding: 0 12px 20px 12px;
      margin-top: 10px;
      display: flex;
      gap: 12px;
    }
  }
}

.upload-progress {
  margin-top: 10px;
  width: 80%;
}

/* 确保地图容器有明确的高度 */
:deep(.amap-container) {
  height: 300px !important;
  width: 100% !important;
}
</style>
